﻿using FlashPay.Service.Company;
using FlashPay.Entity.Request.Company;
using FlashPay.Entity.Response.Company;
using System;
using System.Collections.Generic;
using FlashPay.Util;
using FlashPay.DAO.Interface;
using FlashPay.Util.StatusCode;
using FlashPay.Entity.DAORequest.User;
using FlashPay.Service.Shared;
using FlashPay.EF.Models;
using FlashPay.Entity.Enum;
using FlashPay.Entity;
using FlashPay.Entity.Response.ExtApi;
using FlashPay.Entity.Request.ExtApi;
using FlashPay.Entity.Parameter;
using System.Linq;
using AutoMapper;
using FlashPay.EF;
using FlashPay.DAO.Sys;

namespace FlashPay.Service.Impl.Company
{
    /// <summary>
    /// 公司服務(之後須優化try catch問題)
    /// </summary>
    public class CompanyServiceImpl : BaseService, CompanyService
    {
        private readonly Int32 minCompanyNameLength = 1;
        private readonly Int32 maxCompanyNameLength = 40;
        private readonly StatusCodeFactory statusCodeFactory;

        /// <summary>
        /// 授权接口
        /// </summary>
        private readonly ExtApiCompatDao _extApiCompatDao;

        /// <summary>
        /// 推送接口
        /// </summary>
        private readonly ExtApiPushUrlDao _extApiPushUrlDao;

        /// <summary>
        /// 系统配置接口
        /// </summary>
        private readonly SysConfigDao _sysConfigDao;

        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 上下文
        /// </summary>
        private readonly FlashPayContext _context;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="companyDAO"></param>
        /// <param name="extApiCompatDao"></param>
        /// <param name="extApiPushUrlDao"></param>
        /// <param name="sysRoleDao"></param>
        /// <param name="userInfoDao"></param>
        /// <param name="logDao"></param>
        /// <param name="statusCodeFactory"></param>
        /// <param name="logRecord"></param>
        public CompanyServiceImpl(CompanyDao companyDAO, ExtApiCompatDao extApiCompatDao, ExtApiPushUrlDao extApiPushUrlDao, SysConfigDao sysConfigDao,
                                  IMapper mapper, FlashPayContext context, SysRoleDao sysRoleDao, UserInfoDao userInfoDao,
                                  LogDao logDao, StatusCodeFactory statusCodeFactory, LogRecord logRecord)
        {
            this.companyDAO = companyDAO;

            _extApiCompatDao = extApiCompatDao;
            _extApiPushUrlDao = extApiPushUrlDao;
            _sysConfigDao = sysConfigDao;

            _mapper = mapper;
            _context = context;

            this.sysRoleDao = sysRoleDao;
            this.userInfoDao = userInfoDao;
            this.logDao = logDao;
            this.statusCodeFactory = statusCodeFactory;
            this.logRecord = logRecord;
        }

        #region 映射轉換

        private EF.Models.Company MapperRequest<T>(CompanyRequest<T> model)
        {
            EF.Models.Company request = new EF.Models.Company();

            if (model.CompanyID != null)
                request.CompanyId = (Int32)model.CompanyID;

            request.CompanyPid = model.CompanyPID;
            request.CompanyName = model.CompanyName != null ? model.CompanyName.Trim() : null;
            request.CompanyStatus = model.CompanyStatus;
            request.CompanyBossName = model.CompanyBossName;
            request.CompanyTel = model.CompanyTel;
            request.CompanyAddress = model.CompanyAddress;
            request.CompanyNameEn = model.CompanyNameEN != null ? model.CompanyNameEN.Trim() : null;
            request.CreateUid = model.CreateUID;
            request.CreateDate = model.CreateDate;
            request.UpdateUid = model.UpdateUID;
            request.UpdateDate = model.UpdateDate;
            request.DepositRate = model.DepositRate;
            request.PayRate = model.PayRate;
            request.TransportRate = model.TransportRate;
            return request;
        }

        private CompanyResponse MapperResponse(EF.Models.Company model)
        {
            CompanyResponse response = new CompanyResponse();
            response.CompanyID = model.CompanyId;
            response.CompanyPID = model.CompanyPid;
            response.CompanyName = model.CompanyName;
            response.CompanyStatus = model.CompanyStatus;
            response.CompanyBossName = model.CompanyBossName;
            response.CompanyTel = model.CompanyTel;
            response.CompanyAddress = model.CompanyAddress;
            response.CompanyNameEN = model.CompanyNameEn;
            response.CreateUID = model.CreateUid;
            response.CreateDate = model.CreateDate;
            response.UpdateUID = model.UpdateUid;
            response.UpdateDate = model.UpdateDate;
            response.DepositRate = model.DepositRate;
            response.TransportRate = model.TransportRate;
            response.PayRate = model.PayRate;

            return response;
        }

        #endregion

        #region 
        /// <summary>
        /// 公司新增
        /// </summary>
        public void AddCompany(CompanyRequest<String> model)
        {
            using (companyDAO)
            {
                try
                {
                    #region 公司資料檢查

                    /* 搜尋上層公司 */
                    if (model.CompanyPID > 0)
                    {
                        /* 準備資料 */
                        Entity.DAORequest.Company.CompanyRequest query = CreateCompanyRequest();
                        query.CompanyId = model.CompanyPID;
                        query.CompanyStatus = (SByte)CompanyStatus.开起;

                        /* 取得資料 */
                        EF.Models.Company parentCompany = GetCompany(query);

                        /* 檢查資料 */
                        if (parentCompany == null)
                        {
                            statusCodeFactory.BuildStatus(StatusCode.COMPANY_ADD_CANNOT_FIND_DATA, model);
                            return;
                        }
                    }

                    #endregion

                    #region 公司名稱長度檢查

                    Int32 nameLength = String.IsNullOrWhiteSpace(model.CompanyName) ? 0 : model.CompanyName.Length;
                    if (nameLength < minCompanyNameLength || nameLength > maxCompanyNameLength)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_ADD_NAME_TOO_LONG, model);
                        return;
                    }

                    if (!String.IsNullOrWhiteSpace(model.CompanyNameEN))
                    {
                        Int32 enNameLength = model.CompanyNameEN.Length;
                        if (enNameLength < minCompanyNameLength || enNameLength > maxCompanyNameLength)
                        {
                            statusCodeFactory.BuildStatus(StatusCode.COMPANY_ADD_NAME_TOO_LONG, model);
                            return;
                        }
                    }

                    #endregion

                    #region 公司名稱同名檢查

                    Boolean? checkResult = _CheckCompanyName(model.CompanyName, model.CompanyNameEN);

                    if (checkResult == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        return;
                    }

                    if (!checkResult.Value)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_ADD_EXIST_NAME, model);
                        return;
                    }

                    #endregion

                    /* 轉換Model */
                    EF.Models.Company request = MapperRequest(model);
                    request.CreateDate = GetNowDateTime();

                    /* 呼叫DAO層 */
                    companyDAO.Add(model, request);

                    /* 結果複製 */
                    model.Result = Convert.ToString(request.CompanyId);
                }
                catch (Exception e)
                {
                    /* 新增Log */
                    AddLog(
                        (SByte)LogLevel.Error,
                        (Int32)LogRecordLogType.BranchCompany_Add,
                        model,
                        e.Message
                    );

                    statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);

                    throw;
                }
            }
        }

        /// <summary>
        /// 公司修改
        /// </summary>
        public void EditCompany(CompanyRequest<String> model)
        {
            using (companyDAO)
            {
                try
                {
                    #region 公司資料檢查

                    /* 準備資料 */
                    Entity.DAORequest.Company.CompanyRequest query = CreateCompanyRequest();
                    query.CompanyId = (Int32)model.CompanyID;
                    query.NotCompanyStatus = (SByte)CompanyStatus.删除;

                    /* 如果是修改自己所屬公司，那 CompanyID 與 CompanyPID 理應相同 */
                    if (model.CompanyID != model.CompanyPID)
                    {
                        query.CompanyPid = model.CompanyPID;
                    }

                    /* 取得資料 */
                    EF.Models.Company company = GetCompany(query);

                    /* 檢查資料 */
                    if (company == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_EDIT_CANNOT_FIND_DATA, model);
                        return;
                    }

                    #endregion

                    #region 公司名稱長度檢查

                    Int32 nameLength = String.IsNullOrWhiteSpace(model.CompanyName) ? 0 : model.CompanyName.Length;
                    if (nameLength < minCompanyNameLength || nameLength > maxCompanyNameLength)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_EDIT_NAME_TOO_LONG, model);
                        return;
                    }

                    if (!String.IsNullOrWhiteSpace(model.CompanyNameEN))
                    {
                        Int32 enNameLength = model.CompanyNameEN.Length;
                        if (enNameLength < minCompanyNameLength || enNameLength > maxCompanyNameLength)
                        {
                            statusCodeFactory.BuildStatus(StatusCode.COMPANY_EDIT_NAME_TOO_LONG, model);
                            return;
                        }
                    }

                    #endregion

                    #region 公司名稱同名檢查

                    Boolean? checkResult = _CheckCompanyName(model.CompanyName, model.CompanyNameEN, model.CompanyID);

                    if (checkResult == null)
                    {
                        return;
                    }

                    if (!checkResult.Value)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_EDIT_EXIST_NAME, model);
                        return;
                    }

                    #endregion

                    /* 轉換Model */
                    EF.Models.Company request = MapperRequest(model);
                    request.UpdateDate = GetNowDateTime();

                    if (model.CompanyID == model.CompanyPID)
                    {
                        request.CompanyPid = company.CompanyPid;
                    }

                    /* 呼叫DAO層 */
                    companyDAO.EditUseCompanyIdAndCompanyPid(model, request);
                }
                catch (Exception e)
                {
                    /* 新增Log */
                    AddLog(
                        (SByte)LogLevel.Error,
                        (Int32)LogRecordLogType.BranchCompany_Update,
                        model,
                        e.Message
                    );

                    statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);

                    throw;
                }
            }
        }

        /// <summary>
        /// 公司狀態變更
        /// </summary>
        public void ChangeCompanyStatus(CompanyRequest<String> model)
        {
            using (companyDAO)
            {
                try
                {
                    #region 公司資料檢查

                    /* 準備資料 */
                    Entity.DAORequest.Company.CompanyRequest query = CreateCompanyRequest();
                    query.CompanyId = (Int32)model.CompanyID;
                    query.NotCompanyStatus = (SByte)CompanyStatus.删除;

                    /* 如果是修改自己所屬公司，那 CompanyID 與 CompanyPID 理應相同 */
                    if (model.CompanyID != model.CompanyPID)
                    {
                        query.CompanyPid = model.CompanyPID;
                    }

                    /* 取得資料 */
                    EF.Models.Company company = GetCompany(query);

                    /* 檢查資料 */
                    if (company == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_CHANGE_COMPANY_STATUS_CANNOT_FIND_DATA, model);
                        return;
                    }

                    #endregion

                    /* 補上修改資料 */
                    company.CompanyStatus = model.CompanyStatus;

                    /* 呼叫DAO層 */
                    companyDAO.EditUseCompanyIdAndCompanyPid(model, company);
                }
                catch (Exception e)
                {
                    /* 新增Log */
                    AddLog(
                        (SByte)LogLevel.Error,
                        (Int32)LogRecordLogType.BranchCompany_Update,
                        model,
                        e.Message
                    );

                    statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);

                    throw;
                }
            }
        }

        /// <summary>
        /// 公司刪除(刪除條件: 無用戶、角色存在)
        /// </summary>
        public void DeleteCompany(CompanyRequest<String> model)
        {
            using (companyDAO)
            using (sysRoleDao)
            using (userInfoDao)
            {
                try
                {
                    #region 公司資料檢查

                    /* 準備資料 */
                    Entity.DAORequest.Company.CompanyRequest query = CreateCompanyRequest();
                    query.CompanyId = (Int32)model.CompanyID;
                    query.CompanyPid = model.CompanyPID;
                    query.NotCompanyStatus = (SByte)CompanyStatus.删除;

                    /* 取得資料 */
                    EF.Models.Company company = GetCompany(query);

                    /* 檢查資料 */
                    if (company == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_DELETE_CANNOT_FIND_DATA, model);
                        return;
                    }

                    #endregion

                    #region 角色資料檢查

                    /* 準備資料 */
                    SysRole query2 = new SysRole();
                    query2.RCompanyId = (Int32)model.CompanyID;

                    /* 取得資料 */
                    Int32? sysRole = GetSysRoleCount(query2);

                    /* 檢查資料 */
                    if (sysRole == null)
                    {
                        return;
                    }

                    if (sysRole.Value != 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_DELETE_EXIST_ROLE_DATA, model);
                        return;
                    }

                    #endregion

                    #region 用戶資料檢查

                    /* 準備資料 */
                    UserRequest query3 = new UserRequest();
                    query3.CompanyID = new List<Int32>() { (Int32)model.CompanyID };
                    query3.NotUserStatus = (SByte)UserInfoStatus.删除;

                    /* 取得資料 */
                    Int32? user = GetUserInfoCount(query3);

                    /* 檢查資料 */
                    if (user == null)
                    {
                        return;
                    }

                    if (user != 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.COMPANY_DELETE_EXIST_USER_DATA, model);
                        return;
                    }

                    #endregion

                    /* 補上修改資料 */
                    company.CompanyStatus = (SByte)CompanyStatus.删除;
                    company.CompanyName = company.CompanyName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                    company.CompanyNameEn = company.CompanyNameEn + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");

                    /* 呼叫DAO層 */
                    companyDAO.EditUseCompanyIdAndCompanyPid(model, company);
                }
                catch (Exception e)
                {
                    /* 新增Log */
                    AddLog(
                        (SByte)LogLevel.Error,
                        (Int32)LogRecordLogType.BranchCompany_Delete,
                        model,
                        e.Message
                    );

                    statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);

                    throw;
                }
            }
        }

        /// <summary>
        /// 公司列表
        /// </summary>
        public void GetCompany(CompanyRequest<List<CompanyResponse>> model)
        {
            using (companyDAO)
            {
                Boolean getSelf = false;

                /* 轉換Model */
                Entity.DAORequest.Company.CompanyRequest request = new Entity.DAORequest.Company.CompanyRequest();
                request.CompanyPid = model.CompanyPID;
                request.CompanyName = model.CompanyName != null ? model.CompanyName.Trim() : null;
                request.CompanyStatus = model.CompanyStatus;
                request.CompanyTel = model.CompanyTel;
                request.CompanyNameEn = model.CompanyNameEN != null ? model.CompanyNameEN.Trim() : null;
                request.NotCompanyStatus = model.NotCompanyStatus > 0 ? model.NotCompanyStatus : (SByte)CompanyStatus.删除;

                if (model.CompanyID != null)
                {
                    request.CompanyId = (Int32)model.CompanyID;

                    /* 如果是獲取自己所屬公司，那 CompanyID 與 CompanyPID 理應相同 */
                    if (model.CompanyID == model.CompanyPID)
                    {
                        getSelf = true;
                        request.CompanyPid = -1;
                    }
                }

                if (model.Level < 1)
                {
                    model.Level = 1;
                }

                BaseModel<List<EF.Models.Company>> model2 = new BaseModel<List<EF.Models.Company>>();
                model2.PageIndex = model.PageIndex;
                model2.PageSize = model.PageSize;

                /* 呼叫DAO層 */
                companyDAO.Get(model2, request, model.Level);

                /* 檢查資料 */
                if (!model2.Success)
                {
                    return;
                }

                /* 條件若非獲取自己所屬公司，需再做一次搜索 */
                if (!getSelf && model.CompanyPID > 0)
                {
                    BaseModel<List<EF.Models.Company>> model3 = new BaseModel<List<EF.Models.Company>>();
                    model3.PageIndex = model.PageIndex;
                    model3.PageSize = model.PageSize;

                    request.CompanyId = model.CompanyPID;
                    request.CompanyPid = -1;

                    /* 呼叫DAO層 */
                    companyDAO.Get(model3, request, 1);

                    if (model3.Result != null)
                    {
                        model2.Result.AddRange(model3.Result);
                    }
                }

                /* 轉換Model */
                List<CompanyResponse> result = new List<CompanyResponse>();
                foreach (EF.Models.Company _model in model2.Result)
                {
                    result.Add(MapperResponse(_model));
                }

                /* 結果複製 */
                model.Result = result;
                model.Success = model2.Success;
                model.TotalCount = model2.TotalCount;
            }
        }

        /// <summary>
        /// 公司名稱檢查
        /// </summary>
        public void CheckCompanyName(CompanyRequest<Boolean> model)
        {
            using (companyDAO)
            {
                _CheckCompanyName(model);
            }
        }

        private Boolean? _CheckCompanyName(String companyName, String companyNameEn, Int32? id = null)
        {
            CompanyRequest<Boolean> model = new CompanyRequest<Boolean>();
            model.CompanyName = companyName;
            model.CompanyNameEN = companyNameEn;
            model.CompanyID = id;

            _CheckCompanyName(model);

            if (!model.Success)
            {
                return null;
            }

            return model.Result;
        }

        private void _CheckCompanyName(CompanyRequest<Boolean> model)
        {
            model.Result = true;

            Int32? id = model.CompanyID;
            Boolean flag = false;
            List<EF.Models.Company> result = null;

            Entity.DAORequest.Company.CompanyRequest request = CreateCompanyRequest();
            request.ExactMatch = true;

            if (!String.IsNullOrWhiteSpace(model.CompanyName))
            {
                flag = true;
                request.CompanyName = model.CompanyName.Trim();

                /* 取得資料 */
                result = GetCompanies(request);

                /* 檢查資料 */
                if (result == null)
                {
                    model.Success = false;
                    model.Result = false;
                    return;
                }

                model.Success = true;
                model.Result = result.Count == 0 || result[0].CompanyId == id;
            }

            /* 前面檢查不過或無公司英文名直接返回 */
            if ((flag && !model.Result) || String.IsNullOrWhiteSpace(model.CompanyNameEN))
            {
                return;
            }

            request.CompanyName = null;
            request.CompanyNameEn = model.CompanyNameEN.Trim();

            /* 取得資料 */
            result = GetCompanies(request);

            /* 檢查資料 */
            if (result == null)
            {
                model.Success = false;
                model.Result = false;
                return;
            }

            model.Success = true;
            model.Result = result.Count == 0 || result[0].CompanyId == id;
        }

        /// <summary>
        /// 获取所有公司
        /// </summary>
        /// <returns>List<Company></returns>
        public List<EF.Models.Company> GetList()
        {
            return companyDAO.GetList(new CompanyQuery() { });
        }
        #endregion

        #region 获取授权、推荐地址
        /// <summary>
        /// 获取授权、推荐地址
        /// </summary>
        /// <returns></returns>
        public JResult<ExtApiResponse> GeteExtApi(int companyId)
        {
            var result = new JResult<ExtApiResponse>()
            {
                Success = false
            };

            var extApiResponse = new ExtApiResponse();

            var extApiCompats = _extApiCompatDao.GetList(new ExtApiCompatQuery() { CompanyId = companyId });
            if (extApiCompats != null && extApiCompats.Any())
            {
                var extList = new List<ExtApiResponseNew>();
                extApiCompats.ForEach(item =>
                {
                    extList.Add(new ExtApiResponseNew()
                    {
                        Id = item.Id,
                        CompanyId = item.CompanyId,
                        Type = item.Type,
                        ApiKey = item.ApiKey,
                        Status = item.Status,
                        SecretKey = item.SecretKey
                    });
                });
                extApiResponse.Deposit = GetExtApiResponseModel(extList, ExtApiCompatType.存款.GetHashCode());
                extApiResponse.Payment = GetExtApiResponseModel(extList, ExtApiCompatType.付款.GetHashCode());
                extApiResponse.Transfer = GetExtApiResponseModel(extList, ExtApiCompatType.中转.GetHashCode());
            }

            var extApiPushUrls = _extApiPushUrlDao.GetList(new ExtApiPushUrlQuery() { CompanyId = companyId });
            if (extApiPushUrls != null && extApiPushUrls.Any())
            {
                #region 存款
                var depositExtApiPushUrlType = new List<sbyte>()
                {
                    (sbyte)ExtApiPushUrlType.存款主.GetHashCode(),
                    (sbyte)ExtApiPushUrlType.存款副.GetHashCode()
                };
                extApiResponse.DepositExtApiPushUrlResponse = GetExtApiPushUrlResponse(extApiPushUrls, depositExtApiPushUrlType,false);
                #endregion 

                #region 付款
                var paymentExtApiPushUrlType = new List<sbyte>()
                {
                    (sbyte)ExtApiPushUrlType.付款主.GetHashCode(),
                    (sbyte)ExtApiPushUrlType.付款副.GetHashCode()
                };
                extApiResponse.PaymentExtApiPushUrlResponse = GetExtApiPushUrlResponse(extApiPushUrls, paymentExtApiPushUrlType);
                #endregion

                #region 中转
                var transferExtApiPushUrlType = new List<sbyte>()
                {
                    (sbyte)ExtApiPushUrlType.中转主.GetHashCode(),
                    (sbyte)ExtApiPushUrlType.中转副.GetHashCode()
                };
                extApiResponse.TransferExtApiPushUrlResponse = GetExtApiPushUrlResponse(extApiPushUrls, transferExtApiPushUrlType);
                #endregion
            }

            extApiResponse.DepositVersion = _sysConfigDao.GetVersion("LatestDepositPushVersion");
            extApiResponse.PaymentVersion = _sysConfigDao.GetVersion("LatestWithdrawalPushVersion");
            extApiResponse.TransferVersion = _sysConfigDao.GetVersion("LatestTransportPushVersion");
            result.Success = true;
            result.Data = extApiResponse;
            return result;
        }

        //公共方法(根据类型获取接口授权信息)
        public ExtApiResponseNew GetExtApiResponseModel(List<ExtApiResponseNew> extList, int type)
        {
            var list = extList.FirstOrDefault(p => p.Type == type);
            return list;
        }

        //公共方法(根据类型获取推送地址)
        public List<ExtApiPushUrlResponse> GetExtApiPushUrlResponse(List<ExtApiPushUrl> extApiPushUrls, List<sbyte> depositExtApiPushUrlType,bool isShow=true)
        {
            var extApiPushUrlResponses = new List<ExtApiPushUrlResponse>();
            var commonExtApiPushUrlResponses = extApiPushUrls.Where(p => depositExtApiPushUrlType.Contains(p.Type)).ToList();
            if (commonExtApiPushUrlResponses != null && commonExtApiPushUrlResponses.Any())
            {
                commonExtApiPushUrlResponses.ForEach(item =>
                {
                    var companyName = "";
                    var company = companyDAO.GetById(item.CompanyId);
                    if (company != null)
                    {
                        companyName = company.CompanyName;
                    }

                    ExtApiPushUrlResponse expur = new ExtApiPushUrlResponse();
                    expur.Id = item.Id;
                    expur.CompanyId = item.CompanyId;
                    expur.CompanyName = companyName;
                    expur.Type = item.Type;
                    expur.SortNo = item.SortNo;
                    expur.Status = item.Status;
                    expur.Url = item.Url;
                    expur.Description = item.Description;
                    expur.Version = item.Version;
                    //expur.Version = GetVersion(expur.Type);

                    if (isShow)
                    {
                        expur.PushDeposit = item.PushDeposit;//存款不显示收款记录
                    }
                    extApiPushUrlResponses.Add(expur);
                });
            }
            return extApiPushUrlResponses;
        }
        #endregion

        /// <summary>
        /// 授权编辑(舍弃)
        /// </summary>
        /// <param name="request"></param>
        public JResult ExtApiCompatEdit(List<ExtApiCompatEditRequest> request)
        {
            var result = new JResult()
            {
                Success = false
            };
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    if (request.Count <= 0)
                    {
                        throw new Exception("授权接口参数不能为空！");
                    }
                    request.ForEach(item =>
                    {
                        var typeName = "";
                        if (item.Type == (int)ExtApiCompatType.中转)
                        {
                            typeName = "中转";
                        }
                        else if (item.Type == (int)ExtApiCompatType.付款)
                        {
                            typeName = "付款";
                        }
                        else if (item.Type == (int)ExtApiCompatType.存款)
                        {
                            typeName = "存款";
                        }

                        if (string.IsNullOrEmpty(item.ApiKey))
                        {
                            throw new Exception($"{typeName}ApiKey不能为空！");
                        }
                        if (string.IsNullOrEmpty(item.SecretKey))
                        {
                            throw new Exception($"{typeName}SecretKey不能为空！");
                        }

                        var extApiCompatStatus = new List<SByte>()
                        {
                            (sbyte)ExtApiCompatStatus.启用.GetHashCode(),
                            (sbyte)ExtApiCompatStatus.停用.GetHashCode()
                        };

                        if (!extApiCompatStatus.Contains(item.Status))
                        {
                            throw new Exception($"{typeName}状态错误！");
                        }

                        if (item.Id > 0)
                        {
                            var extApiCompat = _extApiCompatDao.Get(item.Id, item.Type);
                            if (extApiCompat == null)
                            {
                                throw new Exception($"{typeName}记录不存在！");
                            }
                            extApiCompat.ApiKey = item.ApiKey;
                            extApiCompat.SecretKey = item.SecretKey;
                            extApiCompat.Status = item.Status;
                            extApiCompat.Id = item.Id;

                            var updateStatus = _extApiCompatDao.Update(extApiCompat, _context);
                            if (!updateStatus)
                            {
                                throw new Exception($"{typeName}更新失败");
                            }
                        }
                        else
                        {
                            var extApiCompat = new ExtApiCompat()
                            {
                                Type = item.Type,
                                CompanyId = item.CompanyId,
                                ApiKey = item.ApiKey,
                                SecretKey = item.SecretKey,
                                Status = item.Status
                            };

                            var addStatus = _extApiCompatDao.Add(extApiCompat, _context);
                            if (addStatus <= 0)
                            {
                                throw new Exception($"{typeName}新增失败");
                            }
                        }

                    });

                    tran.Commit();

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    result.ErrorMessage = "系统出错";
                    AddLog((SByte)LogLevel.Error, (Int32)LogRecordLogType.BranchCompany_Update, request, "公司接口授权—提交出错：" + ex.Message);
                }
            }

            return result;
        }

        //一个公共的获取版本号方法
        public sbyte GetVersion(int type)
        {
            sbyte version = 2;
            if (type == ExtApiPushUrlType.存款主.GetHashCode() || type == ExtApiPushUrlType.存款副.GetHashCode())
            {
                version = Convert.ToSByte(_sysConfigDao.GetVersion("LatestDepositPushVersion"));
            }
            else if (type == ExtApiPushUrlType.付款主.GetHashCode() || type == ExtApiPushUrlType.付款副.GetHashCode())
            {
                version = Convert.ToSByte(_sysConfigDao.GetVersion("LatestWithdrawalPushVersion"));
            }
            else if (type == ExtApiPushUrlType.中转主.GetHashCode() || type == ExtApiPushUrlType.中转副.GetHashCode())
            {
                version = Convert.ToSByte(_sysConfigDao.GetVersion("LatestTransportPushVersion"));
            }
            return version;
        }

        /// <summary>
        /// 获取推送地址
        /// </summary>
        /// <param name="request"></param>
        public ExtApiPushUrlResponse GetExtApiPushUrl(int id)
        {
            var extApiPushUrlResponse = new ExtApiPushUrlResponse();

            var extApiPushUrl = _extApiPushUrlDao.Get(id);
            if (extApiPushUrl != null)
            {
                extApiPushUrlResponse.Id = extApiPushUrl.Id;
                extApiPushUrlResponse.CompanyId = extApiPushUrl.CompanyId;
                //extApiPushUrlResponse.CompanyName = extApiPushUrl.CompanyName;
                extApiPushUrlResponse.Status = extApiPushUrl.Status;

                sbyte type = extApiPushUrl.Type;
                extApiPushUrlResponse.Type = type;
                extApiPushUrlResponse.SortNo = extApiPushUrl.SortNo;
                extApiPushUrlResponse.Url = extApiPushUrl.Url;
                extApiPushUrlResponse.Description = extApiPushUrl.Description;
                //extApiPushUrlResponse.Version = extApiPushUrl.Version;
                extApiPushUrlResponse.Version = GetVersion(type);

                if (extApiPushUrl.Type > 2)
                {
                    extApiPushUrlResponse.PushDeposit = extApiPushUrl.PushDeposit;
                }
            }
            return extApiPushUrlResponse;
        }

        /// <summary>
        /// 推送地址新增或编辑
        /// </summary>
        /// <param name="request"></param>
        public JResult ExtApiPushUrlAddOrEdit(ExtApiPushUrlAddOrEditRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    if (request.Id <= 0)
                    {
                        if (!request.CompanyId.HasValue)
                        {
                            throw new Exception("推送地址公司参数错误！");
                        }
                    }

                    var extApiPushUrlType = new List<SByte>()
                    {
                        (sbyte)ExtApiPushUrlType.存款主.GetHashCode(),
                        (sbyte)ExtApiPushUrlType.存款副.GetHashCode(),
                        (sbyte)ExtApiPushUrlType.付款主.GetHashCode(),
                        (sbyte)ExtApiPushUrlType.付款副.GetHashCode(),
                        (sbyte)ExtApiPushUrlType.中转主.GetHashCode(),
                        (sbyte)ExtApiPushUrlType.中转副.GetHashCode()
                    };

                    if (!extApiPushUrlType.Contains(request.Type))
                    {
                        throw new Exception("推送地址类型错误！");
                    }

                    var extApiPushUrlStatus = new List<SByte>()
                    {
                        (sbyte)ExtApiPushUrlStatus.启用.GetHashCode(),
                        (sbyte)ExtApiPushUrlStatus.禁用.GetHashCode()
                    };

                    if (!extApiPushUrlStatus.Contains(request.Status))
                    {
                        throw new Exception("推送地址状态错误！");
                    }


                    var extApiPushUrlPara = new ExtApiPushUrlQuery()
                    {
                        Type = request.Type,
                        CompanyId = request.CompanyId
                    };
                    if (request.Id > 0)
                    {
                        extApiPushUrlPara.NotEqualId = request.Id;
                    }
                    var extApiPushUrls = _extApiPushUrlDao.GetList(extApiPushUrlPara);

                    //数据验证
                    if (request.Type == (sbyte)ExtApiPushUrlType.存款主.GetHashCode())
                    {
                        //有且只有一个
                        if (extApiPushUrls != null && extApiPushUrls.Count > 0)
                        {
                            throw new Exception("存款主有且只有一个！");
                        }
                    }
                    else if (request.Type == (sbyte)ExtApiPushUrlType.付款主.GetHashCode())
                    {
                        //有且只有一个
                        if (extApiPushUrls != null && extApiPushUrls.Count > 0)
                        {
                            throw new Exception("付款主有且只有一个！");
                        }
                    }
                    else if (request.Type == (sbyte)ExtApiPushUrlType.中转主.GetHashCode())
                    {
                        //有且只有一个
                        if (extApiPushUrls != null && extApiPushUrls.Count > 0)
                        {
                            throw new Exception("中转主有且只有一个！");
                        }
                    }

                    if (request.Id > 0)
                    {
                        //获取推荐地址
                        var extApiPushUrl = _extApiPushUrlDao.Get(request.Id);
                        if (extApiPushUrl == null)
                        {
                            throw new Exception("推送地址记录不存在！");
                        }

                        extApiPushUrl.Type = request.Type;
                        extApiPushUrl.SortNo = request.SortNo;
                        extApiPushUrl.Status = request.Status;
                        extApiPushUrl.Url = request.Url.Trim();
                        extApiPushUrl.Description = request.Description;
                        extApiPushUrl.Version = request.Version;
                        extApiPushUrl.PushDeposit = request.PushDeposit;

                        var updateStatus = _extApiPushUrlDao.Update(extApiPushUrl, _context);
                        if (!updateStatus)
                        {
                            throw new Exception("更新失败");
                        }

                        tran.Commit();

                        result.Success = true;
                        result.SuccessMessage = "操作成功！";

                    }
                    else
                    {
                        var extApiPushUrl = new ExtApiPushUrl()
                        {
                            CompanyId = request.CompanyId.Value,
                            Type = request.Type,
                            SortNo = request.SortNo,
                            Status = request.Status,
                            Url = request.Url.Trim(),
                            Description = request.Description,
                            Version = request.Version,
                            PushDeposit = request.PushDeposit
                        };

                        var addStatus = _extApiPushUrlDao.Add(extApiPushUrl, _context);
                        if (addStatus <= 0)
                        {
                            throw new Exception("新增失败");
                        }

                        tran.Commit();

                        result.Success = true;
                        result.SuccessMessage = "操作成功！";
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    result.ErrorMessage = "数据已存在";
                    AddLog((SByte)LogLevel.Error, (Int32)LogRecordLogType.BranchCompany_Update, request, "公司授权—新增或编辑推送地址出错：" + ex.Message);
                }

                return result;
            }
        }

        /// <summary>
        /// 推送地址删除
        /// </summary>
        /// <param name="request"></param>
        public JResult ExtApiPushUrlDel(ExtApiPushUrlAddOrEditRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            var rows = _extApiPushUrlDao.ExtApiPushUrlDel(request);
            if (rows > 0)
            {
                result.SuccessMessage = "删除成功";
                result.Success = true;
                /* 新增Log */
                AddLog((SByte)LogLevel.Error, (Int32)LogRecordLogType.BranchCompany_Delete, request, "公司接口授权—推送地址删除");
            }
            else if (rows == -1)
            {
                result.ErrorMessage = "删除异常";
            }

            return result;
        }
    }
}
